//防抖
export function debounce(callback, delay) {
  let timer;
  return function () {
    const thisContext = this
    const thisArguments = Array.from(arguments)
    if (timer) clearTimeout(timer);
    timer = setTimeout(()=>{
      callback.apply(thisContext, thisArguments)
    }, delay);
  }
}


//版本1 时间戳
export function throttleTimestamp(callback, delay) {
  let startTime = +(new Date())
  return function() {
    const thisContext = this
    //事实证明 apply也可以传入伪数组，比如arguments
    const thisArguments = Array.from(arguments)
    const currentTime = +(new Date())
    if(currentTime - startTime >= delay) {
      callback.apply(thisContext, thisArguments)
      startTime = +(new Date())
    }
  }
}

//版本2 定时器
export function throttleSetTimeOut(callback, delay){
  let timer = null
  return function() {
    if(!timer) {
      const thisContext = this
      const thisArguments = Array.from(arguments)
      timer = setTimeout(() => {
        callback.apply(thisContext, thisArguments)
        timer = null
      }, delay)
    }
  }
}


//节流和防抖
// export 
function mergeThrottleDebounce(callback, delay) {
  let startTime = +(new Date())
  let timer = null
  return function() {
    const thisContext = this
    //事实证明 apply也可以传入伪数组，比如arguments
    const thisArguments = Array.from(arguments)
    const currentTime = +(new Date())
    if(currentTime - startTime >= delay) { //超时发车
      callback.apply(thisContext, thisArguments)
      startTime = +(new Date())
    }else { // 未到时间重新发车计时
      if(timer) clearTimeout(timer)
      timer = setTimeout(() => {
        callback.apply(thisContext, thisArguments)
        startTime = +(new Date())
      }, delay)
    }
  }
}